!function () {
    layui.config({base: '/layui/lay/modules/'}).use(['table', 'laydate', 'dateformat','upload', 'form','status','common'], function () {
        //定义
        var $ = layui.jquery,
            table = layui.table,
            form = layui.form,
            upload = layui.upload,
            dateformat = layui.dateformat,
            laydate = layui.laydate,
            layuiSta = layui.status,//自定义状态控件
            common = layui.common;//自定义状态控件

        //定义总变量
        var MenuWeb = {
            tableId: "menuWebTable",    //表格id
            parentType:{'0':'无父级菜单'},              //父菜单节点
            condition: {                //查询条件
                name: "",
                startDate: "",
                endDate: ""
            }
        }

        /****
         * 初始化获取类别
         */
        MenuWeb.initType = function(){
            $.ajax({
                async: false,
                url: '/menuWeb/findParentMenu',
                success: function (result){
                    if (result && result.code == 200) {
                        var pMenu = result.data;
                        $.each(pMenu,function(key,value){
                            if( value !='首页')
                                MenuWeb.parentType[key] = value;
                        });
                    }

                }
            });
        }

        /**
         * 初始化列表列
         * **/
        MenuWeb.initColumn = function(){
            return [[
                /*{type: 'checkbox', fixed: 'left'},*/
                {field: 'id', title: 'ID', width: 80,hide:true},
                {field: 'name', title: '菜单名称', width: 160},
                {field: 'remark', title: '菜单描述', width: 260},
                {field: 'pid' ,title :'父级菜单',width:120,templet:function(row){
                        return MenuWeb.parentType[row.pid];
                    }},
                {field: 'sort' ,title :'菜单排序',width:120},
                {field: 'status' ,title :'菜单显示',width:120,templet:'#statusClo'},
                {field: 'createDate' ,title :'创建时间',width: 165, templet: function (row) {
                        return dateformat.format(common.NewDate(row.createDate), 'yyyy-MM-dd hh:mm:ss');
                    }},
                {field: 'createPerson' ,title :'创建人',width:120},
                {fixed: 'right', title: '操作', toolbar: '#barDemo', width: 280, align: 'center'}
            ]];
        }

        MenuWeb.findParentMenu = function(id){
            $.ajax({
                async: false,
                url: '/menuWeb/findParentMenu',
                success: function (result){
                    if (result && result.code == 200) {
                        var pMenu = result.data;
                        var defaultHtml = '<option value="">请选择</option><option value="0">无父级菜单</option>';
                        var html =defaultHtml+'';
                        $.each(pMenu,function(key,value){
                            if( value != '首页')
                                html += '<option value="'+key+'">'+value+'</option>'
                        });
                        $(id).empty().append(html);
                    }

                }
            });
        }

        /**
         * 查询方法
         * **/
        MenuWeb.search = function(){
            var queryData = {};
            queryData["name"] = $("#name").val();
            queryData["startDate"] = $("#startDate").val();
            queryData["endDate"] = $("#endDate").val();
            table.reload(MenuWeb.tableId, {where: queryData,page: {curr: 1}});
        }

        /**
         * 新增记录
         * **/
        MenuWeb.addRecord =function (){

            //初始化表单
            $('#editForm')[0].reset();
            $('#editForm input,textarea').val("");
            MenuWeb.findParentMenu('#pid');
            layuiSta.initSta("#statusDiv",'',true);//构建状态
            layui.form.render();
            //打开弹出层
            layer.open({
                type: 1, maxmin: true, title: '新增菜单', shade: 0.4, shadeClose: false,
                area: ['700px', '600px'], content: $('#editForm').show(), btn: ['保存', '取消'],
                yes: function () {
                    $('#saveRecord').click();
                }, btn2: function () {
                    layer.closeAll();
                }, end: function () {
                    $('#editForm').hide();
                }
            });
        }

        /**
         * 新增子记录
         * **/
        MenuWeb.addChildRecord =function (data){

            //获取父节点
            var parentId = data.id;
            //初始化表单
            $('#editForm')[0].reset();
            $('#editForm input,textarea').val("");
            MenuWeb.findParentMenu('#pid');
            layuiSta.initSta("#statusDiv",'',true);//构建状态
            form.render('radio').val('editForm', {'pid':parentId});
            //打开弹出层
            layer.open({
                type: 1, maxmin: true, title: '新增子菜单', shade: 0.4, shadeClose: false,
                area: ['700px', '600px'], content: $('#editForm').show(), btn: ['保存', '取消'],
                yes: function () {
                    $('#saveRecord').click();
                }, btn2: function () {
                    layer.closeAll();
                }, end: function () {
                    $('#editForm').hide();
                }
            });
        }

        /**
         * 修改记录
         * **/
        MenuWeb.editRecord =function (data){
            MenuWeb.findParentMenu('#pid');
            //初始化数据
            $.ajax({
                async: false,
                url: '/menuWeb/findMenuWeb?id=' + data.id,
                success: function (result) {
                    if (result && result.code == 200) {
                        var data = result.data;
                        //初始化表单
                        form.render('radio').val('editForm', data);
                        layuiSta.initSta("#statusDiv",data.status,true);//构建状态
                        //打开弹出层
                        layer.open({
                            type: 1, maxmin: true, title: '修改菜单', shade: 0.4, shadeClose: false,
                            area: ['700px', '600px'], content: $('#editForm').show(), btn: ['保存', '取消'],
                            yes: function () {
                                $('#saveRecord').click();
                            }, btn2: function () {
                                layer.closeAll();
                            }, end: function () {
                                $('#editForm').hide();
                            }
                        });
                    }else
                        layer.alert(result.msg || '请求失败了！', {icon: 5, title: '提示'});
                },
                error: function () {
                    layer.alert('服务器出错啦！', {icon: 2, title: '错误'});
                }
            });
        }

        /**
         * 删除记录
         * **/
        MenuWeb.deleteRecord =function (data){
            $.ajax({
                async: false,
                type: 'post',
                url: '/menuWeb/delete?id=' + data.id,
                success: function (result) {
                    if (result && result.code == 200) {
                        layer.alert('操作成功！', {icon: 1, title: '提示'});
                        MenuWeb.search();
                    }
                },
                error: function () {
                    layer.alert('服务器出错啦！', {icon: 2, title: '错误'});
                }
            });
        }

        //初始化渲染列表
        //日期
        var startDate = laydate.render({
            elem: '#startDate',
            done: function(value, date){
                endDate.config.min = date;
                endDate.config.min.month = date.month -1;
            }
        });
        var endDate =  laydate.render({
            elem: '#endDate',
            done: function(value, date){
                if($.trim(value) == ''){
                    var curDate = new Date();
                    date = {'date': curDate.getDate(), 'month': curDate.getMonth()+1, 'year': curDate.getFullYear()};
                }
                startDate.config.max = date;
                startDate.config.max.month = date.month -1;
            }
        });


        //先初始化父菜单
        MenuWeb.initType();

        table.render({
            elem:"#menuWebTable"
            ,url:"/menuWeb/listPage"
            ,cellMinWidth:80
            ,request: {pageName: 'pageNum', limitName: 'pageSize'}
            ,page: true
            ,cols:MenuWeb.initColumn(),
            cellMinHeight:200

        });

        // 搜索按钮点击事件
        $('#btnSearch').click(function () {
            MenuWeb.search();
        });

        // 重置点击事件
        $('#resetSearch').click(function () {
            $('#queryTools input').val('');
            $('#queryTools select').val('');
            MenuWeb.search();
        });

        // 添加按钮点击事件
        $('#btnAdd').click(function () {
            MenuWeb.addRecord();
        });

        //监听工具条
        table.on('tool(' + MenuWeb.tableId + ')',function(obj){
            var data = obj.data;
            var layEvent = obj.event;
            if( layEvent ==='detail'){
                //查看
                return false;
            } else if( layEvent ==='del'){
                layer.confirm('确定要删除该菜单吗？谨慎操作：该菜单将从官网被删除且不可恢复', function (index) {
                    MenuWeb.deleteRecord(data);
                    return false;
                });
            } else if( layEvent ==='edit'){
                MenuWeb.editRecord(data);
                return false;
            } else if( layEvent ==='editChild'){
                MenuWeb.addChildRecord(data);
                return false;
            }
        });

        //监听状态操作
        form.on('switch(setStatus)', function(obj){
            $.ajax({
                async: false,
                type: 'post',
                url: '/menuWeb/setStatus',
                data:{"id":this.value,"status":obj.elem.checked?1:0},
                success: function (result) {
                    if (result && result.code == 200) {
                        layer.tips('修改状态成功', obj.othis);
                    }
                },
                error: function () {
                    layer.alert('修改状态失败', obj.othis);
                }
            });
        });

        //监听提交事件
        form.on('submit(editRecord)',function(data){

            var postUrl = !data.field['id'] ? '/menuWeb/addMenuWeb' : '/menuWeb/editMenuWeb';
            $.ajax({
                async: false, type: 'post', traditional: true, data: data.field, url: postUrl,
                success: function (data) {
                    if (data && data.code == 200) {
                        layer.closeAll();
                        layer.alert('操作成功！', {icon: 1, title: '提示'});
                        MenuWeb.search();
                    } else
                        layer.alert(data.msg || '操作失败了！', {icon: 5, title: '提示'});
                },
                error: function () {
                    layer.closeAll();
                    layer.alert('服务器出错啦！', {icon: 2, title: '错误'});
                }
            });
            return false;
        });

    });
}();